<template>
    <div class="chart" :style="style" ref="chart"></div>
</template>
<script>
let storeChart = {};
import opt from "./opt.js";
import mixin from "./../mixin";
export default {
    name: "Bar",
    mixins: [mixin],
    methods: {
        /**
         * 初始化组件，将组件存储到一个对象里面去，实现vue不挂载echarts对象，
         * 通过Math.random()设置不同的对象，实现多处引用同一个组件的时候不混淆数据
         */
        initChart(params = {}) {
            let paramRender = { ...params };
            this.random = Math.ceil(Math.random() * 100000);
            if (storeChart[this.random]) {
                storeChart[this.random].clear();
            } else {
                storeChart[this.random] = echarts.init(this.$el);
            }
            storeChart[this.random].setOption(opt(paramRender), true);
            this.handleClick();
        },
        getChart() {
            return storeChart[this.random];
        },
        update(params) {
            if (!storeChart[this.random]) return;
            storeChart[this.random].clear();
            storeChart[this.random].setOption(opt(params), true);
        },
        handleResize() {
            if(!storeChart[this.random]){
                return;
            }
            storeChart[this.random].resize();
        },
        /**
         * 点击事件
         */
        handleClick() {
            storeChart[this.random].on("click", (param) => {
                clearTimeout(this.timer);
                this.timer = setTimeout(() => {
                    this.$emit("on-click", param);
                    console.log(param);
                }, 250);
            });
            storeChart[this.random].on("dblclick", (param) => {
                clearTimeout(this.timer);
                this.timer = setTimeout(() => {
                    this.$emit("on-dblclick", param);
                    console.log(param);
                }, 250);
            });
        },
    },
    beforeDestroy() {
        clearTimeout(this.timer);
        if (storeChart[this.random]) {
            storeChart[this.random].dispose();
            storeChart[this.random] = null;
            storeChart = {};
            this.random = "";
            window.removeEventListener("resize", () => {
                this.handleResize();
            });
        }
    },
};
</script>
<style lang="less" scoped>
</style>